<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles'}">权限管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/roles'}">角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="queryInfo.query" placeholder="请输入角色名称" class="input-with-select" clearable @clear="getRolesList">
            <el-button slot="append" icon="el-icon-search" @click="getRolesList" />
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-button type="primary" @click="addRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" style="width: 100%" border strip fit>
        <!-- 展开列 -->
        <el-table-column type="expand" width="70">
          <template v-slot:default="scope">
            <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bdbottom', i1 !== 0 ? 'bdtop': '']" class="c_venter">
              <!-- 渲染一级权限 -->
              <el-col :span="5"> <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }} </el-tag><i class="el-icon-caret-right" /></el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2 !== 0 ? 'bdtop': '']" class="c_venter">
                  <el-col :span="6"> <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag><i class="el-icon-caret-right" /></el-col>
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="id" label="角色Id" width="180" />
        <el-table-column prop="roleName" label="角色名称" width="180" />
        <el-table-column prop="roleDesc" label="描述" width="180" />
        <el-table-column label="操作" width="380">
          <template v-slot:default="scope">
            <el-button type="primary" size="mini" @click="editRoleDialog(scope.row.id)">编辑</el-button>
            <el-button type="success" size="mini" @click="showSetRightDialog(scope.row)">权限</el-button>
            <el-button type="danger" size="mini" @click="removeRoleById(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <!--  :before-close="handleClose" -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="addDialogVisible"
      width="25%"
      :close-on-click-modal="false"
      close-on-press-escape
      show-close
      lock-scroll
      @closed="addDialogClosed"
    >
      <!-- 内容主体区 -->
      <el-form ref="roleInfoFormRef" :model="roleInfoForm" :rules="roleInfoFormRules" label-width="100px" class="demo-ruleForm" style="width: 400px;">
        <el-form-item label="角色名称" prop="roleName">
          <label slot="label">角色名称</label>
          <el-input v-model="roleInfoForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <label slot="label">角色描述</label>
          <el-input v-model="roleInfoForm.roleDesc" placeholder="请输入角色描述" />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="addDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色分配权限对话框 -->
    <!--  :before-close="handleClose" -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      close-on-press-escape
      show-close
      lock-scroll
      @closed="closedDialogClosed"
    >
      <!-- 内容主体区-树形控件 -->
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="defKeys"
        default-expand-all
      />
      <!-- @node-click="handleNodeClick" -->
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="danger" @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 获取角色列表的参数对象
      queryInfo: {
        query: ''
        // pagenum: 1,
        // pagesize: 5
      },
      rolesList: [],
      total: 0,
      // 当前角色id
      roleId: '',
      // 添加用户对话框是否可见
      addDialogVisible: false,
      // 分配权限对话框是否可见
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: { label: 'authName', children: 'children' },
      // 树形控件默认选中的节点数组
      defKeys: [],
      // 对话框标题
      dialogTitle: '',
      isAdd: false,
      // 添加用户的表单数据
      roleInfoForm: {
        id: '',
        roleName: '',
        roleDesc: '',
        children: []
      },
      // 查询到的用户信息对象
      editForm: {},
      // 添加表单的验证规则对象
      roleInfoFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 0, max: 20, message: '角色名称长度在0-20之间', trigger: 'blur' }
        ],
        roleDesc: [
          { message: '请输入角色描述', trigger: 'blur' },
          { min: 0, max: 200, message: '角色描述不得多于200个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败!')
      this.rolesList = res.data
      this.total = res.data.length
      console.log(res)
    },
    addRoleDialog() {
      this.addDialogVisible = true
      this.isAdd = true
      this.dialogTitle = '添加角色'
    },
    addDialogClosed() {
      this.$refs.roleInfoFormRef.resetFields()
      this.addDialogVisible = false
    },
    // 编辑用户对话框
    async editRoleDialog(roleId) {
      this.isAdd = false
      this.dialogTitle = '编辑用户'
      const { data: res } = await this.$http.get('roles/' + roleId)
      console.log(res)
      if (res.meta.status !== 200) {
        res.mg_state = !res.mg_state
        return this.$message.error('查询角色信息失败！')
      }
      this.roleInfoForm = res.data
      this.roleInfoForm.id = res.data.roleId
      // console.log(this.roleInfoForm)
      this.addDialogVisible = true
    },
    // 点击按钮，添加角色
    addRole() {
      this.$refs.roleInfoFormRef.validate(async valid => {
        if (this.isAdd) {
          if (!valid) return
          // 判断是添加角色还是编辑角色
          const { data: res } = await this.$http.post('roles', this.roleInfoForm)
          // 校验响应状态
          if (res.meta.status !== 201) {
            return this.$message.error('添加角色失败！')
          }
          this.$message.success('添加角色成功！')
          this.addDialogClosed()
          this.getRolesList()
          return
        } else {
          const { data: res } = await this.$http.put('roles/' + this.roleInfoForm.id, {
            roleName: this.roleInfoForm.roleName,
            roleDesc: this.roleInfoForm.roleDesc
          })
          // 校验响应状态
          if (res.meta.status !== 200) {
            return this.$message.error('编辑角色失败！')
          }
          this.$message.success('编辑角色成功！')
          this.addDialogClosed()
          this.getRolesList()
          return
        }
      })
    },
    // 根据id删除用户
    async removeRoleById(roleInfo) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm(`确定删除用户【${roleInfo.roleName}】吗？`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'waring'
        // catch捕获点击取消时返回的异常报错
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除！')
      }
      const { data: res } = await this.$http.delete('roles/' + roleInfo.id)
      // 校验响应状态
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRolesList()
      return
    },
    // 根据id删除权限
    async removeRightById(roleInfo, rightId) {
      // 弹框询问是否删除
      const confirmResult = await this.$confirm(`确定删除权限吗？`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'waring'
        // catch捕获点击取消时返回的异常报错
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除！')
      }
      const { data: res } = await this.$http.delete(`roles/${roleInfo.id}/rights/${rightId}`)
      // 校验响应状态
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      this.$message.success('删除权限成功！')
      roleInfo.children = res.data
      return
    },
    // 分配角色权限对话框
    async showSetRightDialog(roleInfo) {
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      // 校验响应状态
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      this.roleId = roleInfo.id
      // 获取角色下的所有已分配的权限
      this.getLeafKeys(roleInfo, this.defKeys)
      console.log(this.defKeys)
      this.setRightDialogVisible = true
      // 保存获取的权限数据到rightsList中
      this.rightsList = res.data
      console.log(this.rightsList)
      // this.$message.success('获取权限数据成功！')
      return
    },
    // 递归，获取角色下所有三级权限的id
    getLeafKeys(node, arr) {
      // 判断是否三级节点,如果当前节点不包含children属性就证明是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框关闭事件
    closedDialogClosed() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      // 校验响应状态
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.getRolesList()
      this.setRightDialogVisible = false
      this.$message.success('分配权限成功')
      return
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
.c_venter {
  align-items: center;
  display: flex;
}
</style>
